import {Modal, Upload, Progress, Button, message, Spin} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { FC } from 'react';
import {useCallback, useEffect, useRef, useState} from 'react';
import { TOKEN } from '@/common/const';
import storage from '@/utils/storage';
import styles from './index.less';
import imgSrc from './plus.svg';
import duiSrc from './dui.svg';
import closeSrc from './x.svg';
import classnames from 'classnames';
import {isVideo} from "@/utils";
import { useAliyunUpload } from '@/pages/pc/components/Upload/AliyunVideoUpload';
import {allGet} from "@/services/pc";

// const { Dragger } = Upload;

const Index: FC<{
  visible?: boolean;
  onCancel?: () => void;
  onOk: (val: any[]) => void;
  action: string;
  payload: any;
  name?: string;
  aliyunVideoRegion: any
  aliyunVideoUserId: any
  getAliyunAuth: any
  refreshAliyunAuth: any
  getContainer?: () => any
}> = ({ visible, onCancel, onOk, action, payload, name = 'file', aliyunVideoRegion, aliyunVideoUserId, getAliyunAuth, refreshAliyunAuth, getContainer }) => {
  const [fileList, setFileList] = useState<any[]>([]);
  const [selected, setSelected] = useState<any[]>([]);
  const fileListRef = useRef<any[]>([])
  const uploadVideo2PhpTimer = useRef<any>();
  const classDetailPicVideoRef = useRef<any>();
  const uploadUrlRef = useRef({});

  const handleUploadSuccess = async (file, field) => {
    if (isVideo(file.name)) {
      file.videoId = file?.response?.videoId;
      const response = await allGet({
        params: {
          version: 'pc1.0',
          mod: 'video',
          do: 'aliyun',
          action: 'upload',
          type: 'course',
          field,
          aid: file.aid || 0,
          filename: file.name,
          videoid: file.videoId,
        },
      });
      if (!response.success) {
        clearTimeout(uploadVideo2PhpTimer.current);
        return;
      }
      file.aid = response?.data?.attachid;
      if (response.success && response.data.attachment) {
        clearTimeout(uploadVideo2PhpTimer.current);
        file.attachment = response.data.attachment;
        console.log(file);
        uploadUrlRef.current = {
          ...uploadUrlRef,
          [file.uid]: response.data.attachment
        };
        // if (field === 'message') {
        //   classDetailPicVideoRef.current.push({ ...file });
        // }
      } else {
        setTimeout(() => {
          handleUploadSuccess(file, field);
        }, 500);
      }
    } else {
      if (field === 'message') {
        classDetailPicVideoRef.current.push({ ...file });
      }
    }
  };
  const { AliyunUploaderRef } = useAliyunUpload({
    region: aliyunVideoRegion,
    userId: aliyunVideoUserId,
    getAliyunAuth,
    refreshAliyunAuth,
    onChange: (_, file) => {
      // const index = fileListRef.current?.findIndex(item => item.uid === file.uid);
      //
      // if (index >= 0) {
      //   const newFileList = [...fileListRef.current];
      //   newFileList[index] = file;
      //   handleChange(newFileList, file);
      // }
    },
    onSuccess: (file) => {
      console.log(file);
      if (file?.response?.videoId) {
        file.videoId = file?.response?.videoId;
      }
      handleUploadSuccess(file, 'message');
      // onSuccess?.([...fileListRef.current], file,)
    },
  });


  const selectAll = useCallback(() => {
    setSelected([...fileList])
  }, [fileList])

  const customRequest = (info: any) => {
    console.log(info)
    if (!isVideo(info.file.name)) {
      message.error('视频仅支持 avi/mp4/mov 格式');
      return;
    }
    fileListRef.current = [...fileListRef.current, {status: 'uploading', uid: info.file.uid}]
    setFileList([...fileListRef.current])
    AliyunUploaderRef.current.addFile(info.file, null, null, null, '{"Vod":{}}');
    AliyunUploaderRef.current.startUpload();
    const timer = setInterval(() => {
      if (uploadUrlRef.current[info.file.uid]) {
        fileListRef.current = [...fileListRef.current].map(item => item.uid === info.file.uid ? ({status: 'done', uid: info.file.uid, url: uploadUrlRef.current[info.file.uid]}) : item)
        setFileList([...fileListRef.current])
        clearInterval(timer);
        delete uploadUrlRef.current[info.file.uid]
      }
    }, 1500);
  }
  const ok = () => {
    if(!selected.length){
      message.error('请先选择插入的视频')
      return
    }
    onOk([...selected])
  }
  const remove = (uid) => {
    setFileList([...fileList].filter(item => item.uid !== uid));
    setSelected([...selected].filter(item => item.uid !== uid));
  }
  useEffect(() => {
    console.log('filelist', fileList);
  }, [fileList]);
  useEffect(() => {
    if(visible === false){
      setSelected([])
    }
  }, [visible])
  return (
    <Modal
      open={visible}
      wrapClassName={classnames('c-lecturer-chapter-modal-wrap-container', styles.container)}
      maskClosable={false}
      closable={false}
      onCancel={onCancel}
      getContainer={getContainer}
      footer={null}
      width={810}
      onOk={ok}
      zIndex={2080}
      okText={'插入所选项'}
    >
      <div style={{ lineHeight: '62px', textAlign: 'center', color: '#E5F5EF', fontSize: 16 }}>
        上传视频
      </div>
      <div className={styles.upload} style={{ padding: '0 20px' }}>
        <Upload
          action={action}
          accept='.avi, .mp4, .mov'
          customRequest={customRequest}
          listType="picture-card"
          fileList={fileList}
          // showUploadList={false}
          multiple
          // onChange={handleChange}
          data={payload}
          name={name}
          headers={{
            token: (storage.get(TOKEN) || {}).value,
          }}
        >
          <img width={36} height={36} src={imgSrc} alt="" />
        </Upload>
        {fileList?.map((item, index) => {
          return (
            <Spin
              spinning={item.status !== 'done'}
              key={index === fileList.length -1 ? JSON.stringify(item) + Date.now() : JSON.stringify(item)}
              tip="上传中..."
            >
              <span
                className={classnames(styles.img, {
                  [styles.selected]: selected.some((it) => it.uid === item.uid),
                })}
                onClick={() => {
                  if(selected.some((it) => it.uid === item.uid)){
                    setSelected([...selected].filter(it => it.uid !== item.uid))
                  }else{
                    setSelected([...selected, item])
                  }
                }}
              >
              {/*<img key={item.status} src={item.response?.data?.url || item.thumbUrl} alt="" />*/}
                <video style={{width: 120, height: 120}} key={item.status} src={item.url} />
              <i onClick={() => remove(item.uid)} className={styles.close} />
            </span>
            </Spin>
          );
        })}
      </div>
      <div className={styles.footer}>
        <span>
          <span onClick={selectAll}><img src={duiSrc} alt=""/>选择全部</span>
          <span onClick={() => setSelected([])}><img src={closeSrc} alt=""/>取消全部</span>
        </span>
        <span>
          <Button onClick={onCancel}>取消</Button>
          <Button onClick={ok} type='primary'>插入所选项</Button>
        </span>
      </div>
    </Modal>
  );
};

export default Index;
